Set 1: API Versioning & Documentation (Swagger, OpenAPI)

Audio 1 - Audio 2

1. What is API versioning and why is it important?

Answer: API versioning is a technique used to manage changes in an API over time, ensuring backward compatibility and smooth integration for clients. It is important to avoid breaking changes for existing users while introducing new features and improvements.

2. How can API versioning be implemented in a REST API?

Answer: API versioning can be implemented in a REST API using URL path versioning, query parameter versioning, or header versioning. For example:

3. What is Swagger, and how does it help in documenting APIs?

Answer: Swagger is a framework that helps in designing, building, and documenting RESTful APIs. It generates interactive API documentation, making it easier for developers to understand and use the API. It also provides tools for testing API endpoints directly from the documentation.

4. What is OpenAPI, and how does it relate to Swagger?

Answer: OpenAPI is a specification for describing RESTful APIs. Swagger is a set of tools built around OpenAPI, such as Swagger UI and Swagger Codegen, which help in generating and consuming OpenAPI definitions. OpenAPI is the specification, while Swagger provides the implementation tools.

5. What is the purpose of the @Api annotation in Swagger?

Answer: The @Api annotation is used at the class level in Swagger to describe the entire API. It provides metadata such as the title, description, and tags to organize API methods. Example:

        @Api(value = "User Management", description = "Operations related to user management")
        @RestController
        public class UserController { ... }
        

6. How do you define an API operation in Swagger?

Answer: An API operation is defined using the @ApiOperation annotation. This annotation is applied to the method and provides details about the operation, such as its description, HTTP method, and response type. Example:

        @ApiOperation(value = "Get user by ID", response = User.class)
        @GetMapping("/user/{id}")
        public User getUser(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

7. How do you include parameter descriptions in Swagger documentation?

Answer: Parameter descriptions can be included using the @ApiParam annotation. This annotation allows you to specify details such as whether the parameter is required and provide a description. Example:

        @ApiOperation(value = "Get user by ID")
        @GetMapping("/user/{id}")
        public User getUser(@ApiParam(value = "ID of the user to be retrieved", required = true) @PathVariable Long id) {
            return userService.getUserById(id);
        }
        

8. How can you specify response status codes in Swagger?

Answer: Response status codes can be specified using the @ApiResponse annotation. This annotation is used to define different status codes and the corresponding response messages. Example:

        @ApiOperation(value = "Create a new user")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully created user"),
            @ApiResponse(code = 400, message = "Bad request")
        })
        @PostMapping("/user")
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }
        

9. How can you handle authentication in Swagger?

Answer: Authentication in Swagger can be handled by defining security schemes, such as API keys, OAuth2, or basic authentication, in the Swagger configuration. Example:

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .securitySchemes(Arrays.asList(new BasicAuth("basicAuth")))
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example"))
                        .paths(PathSelectors.any())
                        .build();
            }
        }
        

10. What is the role of the @ApiModel annotation in Swagger?

Answer: The @ApiModel annotation is used to describe a model class (data object) in Swagger. It provides metadata about the model, such as its description, which helps generate better API documentation. Example:

        @ApiModel(description = "Details about the user")
        public class User {
            @ApiModelProperty(notes = "The unique ID of the user")
            private Long id;
            @ApiModelProperty(notes = "The user's name")
            private String name;
            // getters and setters
        }
        

 

Set 2: API Versioning & Documentation (Swagger, OpenAPI)

11. How can you use Swagger UI to test API endpoints?

Answer: Swagger UI provides an interactive interface where users can explore and test API endpoints. By visiting the Swagger UI page, users can click on available endpoints, input parameters, and execute requests directly from the UI to see the response.

12. How do you specify the base path for the API in Swagger?

Answer: The base path for the API can be specified in the Swagger configuration by using the path method in the Docket bean. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build()
                    .pathMapping("/api/v1");
        }
        

13. What is the difference between Swagger 2 and OpenAPI 3?

Answer: Swagger 2 is the older version of the Swagger specification, whereas OpenAPI 3 is an updated and more feature-rich specification. OpenAPI 3 includes enhanced support for components, better security definitions, improved parameter handling, and more comprehensive documentation features compared to Swagger 2.

14. How can you enable CORS support in Swagger for cross-origin requests?

Answer: CORS (Cross-Origin Resource Sharing) can be enabled by adding a CORS filter in the Spring configuration. Example:

        @Configuration
        public class WebConfig implements WebMvcConfigurer {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        }
        

15. How do you generate a Swagger documentation file in JSON or YAML format?

Answer: Swagger can generate the documentation file in JSON or YAML format by accessing the /v2/api-docs endpoint. For example, visiting http://localhost:8080/v2/api-docs will generate the Swagger JSON documentation. This can be saved or converted into YAML format using tools like Swagger Editor.

16. What are the advantages of using versioning in APIs?

Answer: API versioning allows you to introduce new features and changes in the API without affecting existing consumers. It provides backward compatibility, avoids breaking changes, and enables developers to make improvements while maintaining support for legacy users.

17. How can you make an API versioning strategy flexible?

Answer: An API versioning strategy can be made flexible by choosing a versioning method that suits the needs of the API consumers. For example, using semantic versioning in the header or using path versioning allows clients to opt into the version that best fits their use case, providing more flexibility in how changes are introduced.

18. How do you specify a deprecated API method in Swagger?

Answer: In Swagger, you can use the @ApiOperation annotation with the deprecated flag set to true to indicate that an API method is deprecated. Example:

        @ApiOperation(value = "Get deprecated user data", deprecated = true)
        @GetMapping("/user/old")
        public User getOldUserData(@PathVariable Long id) {
            return userService.getOldUserData(id);
        }
        

19. What is the purpose of the @ApiResponse annotation in Swagger?

Answer: The @ApiResponse annotation is used to specify details about the response of an API operation, such as the status code, message, and response type. It helps in providing detailed documentation for each possible response to an API endpoint.

20. How can you handle custom response types in Swagger?

Answer: Custom response types can be handled in Swagger by defining a custom class or model and associating it with the API operation using the @ApiResponse annotation. Example:

        @ApiOperation(value = "Get custom response")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success", response = CustomResponse.class)
        })
        @GetMapping("/custom")
        public CustomResponse getCustomResponse() {
            return new CustomResponse("Custom data");
        }
        

Set 3: API Versioning & Documentation (Swagger, OpenAPI)

21. How do you define a custom model in Swagger for complex response data?

Answer: You can define a custom model in Swagger by creating a POJO (Plain Old Java Object) class and annotating it with @ApiModel and @ApiModelProperty. Example:

        @ApiModel(description = "User details model")
        public class User {
            @ApiModelProperty(value = "The user's ID", required = true)
            private Long id;
            @ApiModelProperty(value = "The user's name")
            private String name;
            // Getters and setters
        }
        

22. How do you handle request validation in Swagger documentation?

Answer: Request validation in Swagger documentation can be done by annotating the request parameters or body with Java Bean Validation annotations such as @NotNull, @Size, or @Email. Swagger will automatically display these constraints in the documentation. Example:

        public class UserRequest {
            @NotNull
            @Size(min = 1, max = 100)
            private String name;
            @Email
            private String email;
            // Getters and setters
        }
        

23. How do you document different response types in Swagger for the same endpoint?

Answer: You can document different response types for the same endpoint in Swagger using the @ApiResponses annotation, where you specify each possible response code and the corresponding response class. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses({
            @ApiResponse(code = 200, message = "Success", response = User.class),
            @ApiResponse(code = 404, message = "User not found")
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return userService.findById(id)
                    .map(user -> ResponseEntity.ok(user))
                    .orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).build());
        }
        

24. How do you configure a custom error response in Swagger?

Answer: A custom error response can be configured by creating an error response model and using @ApiResponse with a custom class. Example:

        @ApiModel(description = "Error response")
        public class ErrorResponse {
            private String message;
            private int code;
            // Getters and setters
        }
        

25. How do you handle pagination in API responses using Swagger?

Answer: Pagination can be handled in Swagger by defining a response model that includes metadata such as total pages, current page, and items per page, along with the actual data. Example:

        @ApiModel(description = "Paginated response")
        public class PaginatedResponse {
            private List data;
            private int totalPages;
            private int currentPage;
            // Getters and setters
        }
        

26. How do you enable JWT authentication in Swagger UI?

Answer: JWT authentication can be enabled in Swagger UI by configuring the Swagger API documentation to accept an Authorization header with a JWT token. This can be done by using the securitySchemes and security configuration. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Arrays.asList(new ApiKey("JWT", HttpHeaders.AUTHORIZATION, In.HEADER)))
                    .security(Arrays.asList(new SecurityReference("JWT", new AuthorizationScope[0])));
        }
        

27. What is the purpose of the @ApiOperation annotation in Swagger?

Answer: The @ApiOperation annotation is used to provide additional information about a specific API operation (endpoint), such as its description, expected responses, and other metadata like whether it is deprecated or not. Example:

        @ApiOperation(value = "Get user details", notes = "Returns user data by ID")
        @GetMapping("/users/{id}")
        public User getUser(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

28. How do you handle multiple versions of an API using Swagger?

Answer: Multiple versions of an API can be handled in Swagger by creating separate Docket beans for each version and setting the base path accordingly. Example:

        @Bean
        public Docket apiV1() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v1")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v1"))
                    .paths(PathSelectors.any())
                    .build();
        }

        @Bean
        public Docket apiV2() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v2")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v2"))
                    .paths(PathSelectors.any())
                    .build();
        }
        

29. How can you display models in Swagger that are referenced from other models?

Answer: In Swagger, you can reference models in other models by using @ApiModelProperty annotations to point to other model classes. Example:

        @ApiModel(description = "Order model")
        public class Order {
            @ApiModelProperty(value = "The customer details")
            private Customer customer;
            // Getters and setters
        }
        

30. How do you manage Swagger documentation for different environments (e.g., development, production)?

Answer: Swagger documentation for different environments can be managed by using different Swagger configurations based on the active profiles. For example, you can have a @Profile annotation to load different Docket beans based on the active Spring profile. Example:

        @Bean
        @Profile("dev")
        public Docket apiDev() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build();
        }
        

 

Set 4: API Versioning & Documentation (Swagger, OpenAPI)

31. How do you document an endpoint that requires query parameters in Swagger?

Answer: You can document query parameters in Swagger by using the @RequestParam annotation and specifying it with @ApiParam to provide additional metadata like description and default value. Example:

        @ApiOperation(value = "Get users by age", notes = "This endpoint filters users by age")
        @GetMapping("/users")
        public List getUsersByAge(
            @ApiParam(value = "The age of the user", defaultValue = "30") @RequestParam int age) {
            return userService.getUsersByAge(age);
        }
        

32. How do you define a path parameter in Swagger documentation?

Answer: You define a path parameter in Swagger by using the @PathVariable annotation in your method parameters and annotating it with @ApiParam for additional documentation. Example:

        @ApiOperation(value = "Get user details by ID")
        @GetMapping("/users/{id}")
        public User getUserById(
            @ApiParam(value = "The user's ID", required = true) @PathVariable Long id) {
            return userService.getUserById(id);
        }
        

33. How do you exclude certain methods or classes from Swagger documentation?

Answer: You can exclude methods or classes from Swagger documentation using the @ApiIgnore annotation. Example:

        @ApiIgnore
        @GetMapping("/excluded-endpoint")
        public String excludedEndpoint() {
            return "This endpoint is excluded from Swagger documentation.";
        }
        

34. How do you handle the versioning of your API using Swagger?

Answer: API versioning in Swagger can be handled by setting different base paths for each version. You can create separate Docket beans for each version and specify the version in the path. Example:

        @Bean
        public Docket apiV1() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v1")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v1"))
                    .paths(PathSelectors.any())
                    .build();
        }

        @Bean
        public Docket apiV2() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v2")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v2"))
                    .paths(PathSelectors.any())
                    .build();
        }
        

35. How do you specify that an endpoint consumes a specific media type in Swagger?

Answer: You can specify the consumes media type using the @RequestMapping annotation with the consumes attribute, or you can use the @ApiOperation annotation to specify the supported content types. Example:

        @ApiOperation(value = "Create new user", consumes = "application/json")
        @PostMapping("/users")
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }
        

36. How do you document a multipart file upload in Swagger?

Answer: To document a multipart file upload in Swagger, use @RequestParam for the file parameter and annotate it with @ApiParam. Example:

        @ApiOperation(value = "Upload user profile picture")
        @PostMapping("/users/{id}/upload")
        public ResponseEntity uploadUserProfilePicture(
            @PathVariable Long id,
            @RequestParam("file") @ApiParam(value = "Profile picture file") MultipartFile file) {
            userService.uploadProfilePicture(id, file);
            return ResponseEntity.ok().build();
        }
        

37. How do you add authentication support to your Swagger UI?

Answer: You can add authentication support to Swagger UI by configuring a security scheme for JWT or Basic Authentication. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Arrays.asList(new ApiKey("JWT", HttpHeaders.AUTHORIZATION, In.HEADER)))
                    .security(Arrays.asList(new SecurityReference("JWT", new AuthorizationScope[0])));
        }
        

38. How do you specify the parameter types in Swagger?

Answer: Parameter types in Swagger are specified using annotations like @RequestParam, @RequestBody, or @PathVariable, along with @ApiParam to provide additional metadata like description, default value, and required status. Example:

        @ApiOperation(value = "Get user by ID")
        @GetMapping("/users/{id}")
        public User getUserById(
            @ApiParam(value = "User ID", required = true) @PathVariable Long id) {
            return userService.getUserById(id);
        }
        

39. How do you enable Swagger documentation for a Spring Boot application?

Answer: To enable Swagger documentation in a Spring Boot application, add the Swagger dependencies to your pom.xml file and configure the Swagger Docket bean in a configuration class. Example:

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example"))
                        .paths(PathSelectors.any())
                        .build();
            }
        }
        

40. How do you document query parameters as required in Swagger?

Answer: You can document query parameters as required by setting the required attribute of the @RequestParam annotation to true, and use @ApiParam for further documentation. Example:

        @ApiOperation(value = "Get users by name")
        @GetMapping("/users")
        public List getUsersByName(
            @ApiParam(value = "Name of the user", required = true) @RequestParam String name) {
            return userService.getUsersByName(name);
        }
        

 

Set 5: API Versioning & Documentation (Swagger, OpenAPI)

41. How do you configure Swagger for multiple versions of an API?

Answer: To configure Swagger for multiple versions of an API, you can create separate Docket beans for each version, each with its own base package and path settings. Example:

        @Bean
        public Docket apiV1() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v1")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v1"))
                    .paths(PathSelectors.any())
                    .build();
        }

        @Bean
        public Docket apiV2() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .groupName("v2")
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example.v2"))
                    .paths(PathSelectors.any())
                    .build();
        }
        

42. How do you define custom error responses in Swagger?

Answer: You can define custom error responses in Swagger by using @ApiResponse to specify different HTTP statuses and descriptions. Example:

        @ApiOperation(value = "Get user by ID", response = User.class)
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful retrieval of user"),
            @ApiResponse(code = 404, message = "User not found"),
            @ApiResponse(code = 500, message = "Internal server error")
        })
        @GetMapping("/users/{id}")
        public User getUserById(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

43. How do you document a POST method with a request body in Swagger?

Answer: You document a POST method with a request body in Swagger using the @RequestBody annotation and @ApiParam for additional documentation. Example:

        @ApiOperation(value = "Create a new user")
        @PostMapping("/users")
        public User createUser(@ApiParam(value = "User object to be created", required = true) @RequestBody User user) {
            return userService.createUser(user);
        }
        

44. How do you add descriptions to parameters in Swagger?

Answer: You can add descriptions to parameters in Swagger by using the @ApiParam annotation and specifying a description value. Example:

        @ApiOperation(value = "Get user details")
        @GetMapping("/users/{id}")
        public User getUserById(
            @ApiParam(value = "ID of the user to retrieve", required = true) @PathVariable Long id) {
            return userService.getUserById(id);
        }
        

45. How do you configure Swagger for basic authentication?

Answer: You can configure Swagger for basic authentication by specifying a security scheme in the Swagger configuration. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Arrays.asList(new BasicAuth("basicAuth")));
        }
        

46. How do you document an optional query parameter in Swagger?

Answer: You can document an optional query parameter in Swagger by using the @RequestParam annotation with required = false and providing additional metadata using @ApiParam. Example:

        @ApiOperation(value = "Get users by name")
        @GetMapping("/users")
        public List getUsersByName(
            @ApiParam(value = "Name of the user", required = false) @RequestParam(required = false) String name) {
            return userService.getUsersByName(name);
        }
        

47. How do you customize Swagger UI appearance?

Answer: You can customize the appearance of Swagger UI by modifying the swagger-ui.html file or by passing options via the Swagger configuration. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .useDefaultResponseMessages(false)
                    .apiInfo(apiInfo());
        }

        private ApiInfo apiInfo() {
            return new ApiInfo(
                "My API",
                "API documentation for My Service",
                "v1",
                "Terms of service URL",
                new Contact("John Doe", "www.example.com", "john@example.com"),
                "License",
                "License URL",
                Collections.emptyList()
            );
        }
        

48. How do you specify multiple response types for an endpoint in Swagger?

Answer: You can specify multiple response types for an endpoint using @ApiResponses to define the possible HTTP status codes and their corresponding response classes. Example:

        @ApiOperation(value = "Get user details", response = User.class)
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successful retrieval", response = User.class),
            @ApiResponse(code = 404, message = "User not found")
        })
        @GetMapping("/users/{id}")
        public User getUserById(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

49. How do you generate an OpenAPI specification from Swagger annotations?

Answer: You can generate an OpenAPI specification from Swagger annotations by using a tool like Swagger Codegen or OpenAPI Generator, which will create an OpenAPI-compliant document from the annotations in your code. Example:

        swagger-codegen generate -i http://localhost:8080/v2/api-docs -l openapi -o openapi_output/
        

50. How do you document a deprecated method in Swagger?

Answer: You can document a deprecated method in Swagger by using the @ApiOperation annotation with the deprecated = true attribute. Example:

        @ApiOperation(value = "Get user by ID", deprecated = true)
        @GetMapping("/users/{id}")
        public User getUserById(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

 

Set 6: API Versioning & Documentation (Swagger, OpenAPI)

51. How do you document an API endpoint with a file upload in Swagger?

Answer: You can document an API endpoint with a file upload by using the @RequestParam annotation and specifying consumes = "multipart/form-data". Example:

        @ApiOperation(value = "Upload user profile picture")
        @PostMapping(value = "/users/{id}/upload", consumes = "multipart/form-data")
        public ResponseEntity uploadFile(
            @PathVariable Long id,
            @RequestParam("file") MultipartFile file) {
            return ResponseEntity.ok("File uploaded successfully");
        }
        

52. How can you add a description to the Swagger documentation?

Answer: You can add a description to the Swagger documentation by using the @ApiOperation annotation. Example:

        @ApiOperation(value = "Get all users", notes = "This API retrieves all the users in the system.")
        @GetMapping("/users")
        public List getAllUsers() {
            return userService.getAllUsers();
        }
        

53. How do you use Swagger with Spring Security?

Answer: You can use Swagger with Spring Security by configuring Swagger to ignore security constraints or by defining security schemes for authentication in the Swagger configuration. Example:

        @Configuration
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .securitySchemes(Arrays.asList(new BasicAuth("basicAuth")))
                        .select()
                        .apis(RequestHandlerSelectors.any())
                        .paths(PathSelectors.any())
                        .build();
            }
        }
        

54. How do you add tags to group your Swagger documentation?

Answer: You can add tags to group your Swagger documentation by using the @Api annotation at the class level or using @ApiOperation at the method level. Example:

        @Api(tags = "User Management")
        @RestController
        public class UserController {
            @ApiOperation(value = "Get all users")
            @GetMapping("/users")
            public List getAllUsers() {
                return userService.getAllUsers();
            }
        }
        

55. How do you enable Swagger documentation only for certain profiles?

Answer: You can enable Swagger documentation only for certain profiles by using a conditional @Profile annotation or setting the spring.profiles.active property. Example:

        @Profile("dev")
        @Configuration
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .select()
                        .apis(RequestHandlerSelectors.any())
                        .paths(PathSelectors.any())
                        .build();
            }
        }
        

56. How do you create an API documentation with OAuth2 authentication in Swagger?

Answer: You can create API documentation with OAuth2 authentication by configuring Swagger to use OAuth2 security schemes. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .securitySchemes(Arrays.asList(new OAuth("oauth2", authorizationScopes())))
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build();
        }

        private AuthorizationScope[] authorizationScopes() {
            return new AuthorizationScope[] {
                new AuthorizationScope("read", "Read access to the API"),
                new AuthorizationScope("write", "Write access to the API")
            };
        }
        

57. How do you define a custom model for the request and response bodies in Swagger?

Answer: You define a custom model for the request and response bodies in Swagger by creating a Java class and annotating it with @ApiModel and its properties with @ApiModelProperty. Example:

        @ApiModel(description = "User details")
        public class User {
            @ApiModelProperty(value = "User's name", required = true)
            private String name;

            @ApiModelProperty(value = "User's age")
            private int age;
        }

        @ApiOperation(value = "Create a new user")
        @PostMapping("/users")
        public User createUser(@RequestBody User user) {
            return userService.createUser(user);
        }
        

58. How do you add custom response messages to your API endpoints in Swagger?

Answer: You can add custom response messages to your API endpoints in Swagger by using @ApiResponse annotations. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved user"),
            @ApiResponse(code = 404, message = "User not found"),
            @ApiResponse(code = 500, message = "Internal server error")
        })
        @GetMapping("/users/{id}")
        public User getUserById(@PathVariable Long id) {
            return userService.getUserById(id);
        }
        

59. How do you define a custom model for a request body with nested objects in Swagger?

Answer: You define a custom model with nested objects by creating Java classes for the nested models and using @ApiModel and @ApiModelProperty annotations. Example:

        @ApiModel(description = "User details")
        public class User {
            @ApiModelProperty(value = "User's name", required = true)
            private String name;

            @ApiModelProperty(value = "User's address")
            private Address address;
        }

        @ApiModel(description = "Address details")
        public class Address {
            @ApiModelProperty(value = "Street address")
            private String street;
        }
        

60. How do you document a method with a response that has a status code of 202 (Accepted)?

Answer: You can document a method with a response that has a status code of 202 by using the @ApiResponse annotation. Example:

        @ApiOperation(value = "Accept a request")
        @ApiResponses(value = {
            @ApiResponse(code = 202, message = "Request accepted")
        })
        @PostMapping("/request")
        public ResponseEntity acceptRequest() {
            return ResponseEntity.accepted().body("Request accepted");
        }
        

 

Set 7: API Versioning & Documentation (Swagger, OpenAPI)

61. How do you document multiple versions of the same API in Swagger?

Answer: You can document multiple versions of the same API in Swagger by using the groupName property in your Swagger configuration and separating your APIs into different groups based on version. Example:

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            @Bean
            public Docket apiV1() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .groupName("v1")
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example.api.v1"))
                        .paths(PathSelectors.any())
                        .build();
            }

            @Bean
            public Docket apiV2() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .groupName("v2")
                        .select()
                        .apis(RequestHandlerSelectors.basePackage("com.example.api.v2"))
                        .paths(PathSelectors.any())
                        .build();
            }
        }
        

62. How do you add API documentation for deprecated endpoints in Swagger?

Answer: You can add API documentation for deprecated endpoints in Swagger by using the @ApiOperation annotation with the deprecated = true parameter. Example:

        @ApiOperation(value = "Get all users (deprecated)", deprecated = true)
        @GetMapping("/users/old")
        public List getOldUsers() {
            return userService.getAllUsers();
        }
        

63. How do you add metadata like API title and description in Swagger documentation?

Answer: You can add metadata like API title and description in Swagger documentation by using the @EnableSwagger2 annotation and configuring a Docket bean. Example:

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                        .select()
                        .apis(RequestHandlerSelectors.any())
                        .paths(PathSelectors.any())
                        .build()
                        .apiInfo(new ApiInfo(
                                "My API",
                                "This is an API documentation example",
                                "1.0",
                                "Terms of service URL",
                                new Contact("API Author", "URL", "author@domain.com"),
                                "License",
                                "License URL"
                        ));
            }
        }
        

64. How do you exclude certain API endpoints from Swagger documentation?

Answer: You can exclude certain API endpoints from Swagger documentation by using the @ApiIgnore annotation or by configuring Swagger to exclude paths. Example:

        @ApiIgnore
        @GetMapping("/secret")
        public String getSecretInfo() {
            return "This endpoint is excluded from Swagger documentation";
        }
        

65. How do you add request parameters to Swagger documentation?

Answer: You can add request parameters to Swagger documentation by using the @ApiParam annotation on method parameters. Example:

        @ApiOperation(value = "Get user by ID")
        @GetMapping("/users/{id}")
        public User getUserById(@ApiParam(value = "ID of the user", required = true) @PathVariable Long id) {
            return userService.getUserById(id);
        }
        

66. How do you specify response status codes and messages in Swagger?

Answer: You can specify response status codes and messages in Swagger using the @ApiResponse annotation. Example:

        @ApiOperation(value = "Get all users")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Successfully retrieved users"),
            @ApiResponse(code = 500, message = "Internal server error")
        })
        @GetMapping("/users")
        public List getAllUsers() {
            return userService.getAllUsers();
        }
        

67. How do you define query parameters in Swagger documentation?

Answer: You can define query parameters in Swagger documentation by using the @RequestParam annotation along with @ApiParam for documentation. Example:

        @ApiOperation(value = "Search users by name")
        @GetMapping("/users")
        public List searchUsers(
            @ApiParam(value = "Name of the user to search", required = true) @RequestParam String name) {
            return userService.searchUsers(name);
        }
        

68. How do you add a header parameter to Swagger documentation?

Answer: You can add a header parameter to Swagger documentation by using the @RequestHeader annotation along with @ApiParam for documentation. Example:

        @ApiOperation(value = "Get user by header information")
        @GetMapping("/users")
        public User getUserByHeader(
            @ApiParam(value = "User's API key", required = true) @RequestHeader String apiKey) {
            return userService.getUserByApiKey(apiKey);
        }
        

69. How do you document API responses with different content types in Swagger?

Answer: You can document API responses with different content types by using the @ApiResponse annotation and specifying consumes and produces attributes. Example:

        @ApiOperation(value = "Create a new user", consumes = "application/json", produces = "application/json")
        @PostMapping("/users")
        public ResponseEntity createUser(@RequestBody User user) {
            return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
        }
        

70. How do you document a RESTful API with OpenAPI 3.0?

Answer: You can document a RESTful API with OpenAPI 3.0 by using annotations like @OpenAPIDefinition and @Operation in your Spring configuration. Example:

        @OpenAPIDefinition(
            info = @Info(
                title = "My API",
                version = "1.0",
                description = "API documentation using OpenAPI 3.0"
            )
        )
        @RestController
        public class UserController {
            @Operation(summary = "Get all users")
            @GetMapping("/users")
            public List getAllUsers() {
                return userService.getAllUsers();
            }
        }
        

 

Set 8: API Versioning & Documentation (Swagger, OpenAPI)

71. How do you add an example value for a request body in Swagger?

Answer: You can add an example value for a request body in Swagger using the @RequestBody annotation with the @ExampleObject for the body. Example:

        @ApiOperation(value = "Create new user")
        @PostMapping("/users")
        public ResponseEntity createUser(
            @ApiParam(value = "User data", required = true) @RequestBody @ExampleObject(value = "{ \"name\": \"John\", \"age\": 30 }") User user) {
            return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
        }
        

72. How do you document API headers with specific types and formats in OpenAPI?

Answer: You can document API headers with specific types and formats in OpenAPI using the headers section within the operation object. Example:

        @GetMapping("/users")
        @Operation(
            summary = "Get users with specific headers",
            parameters = {
                @Parameter(name = "Authorization", in = ParameterIn.HEADER, required = true, schema = @Schema(type = "string", format = "uuid"))
            }
        )
        public List getUsers(@RequestHeader String authorization) {
            return userService.getUsers(authorization);
        }
        

73. How do you define a request body schema in OpenAPI 3.0?

Answer: You define a request body schema in OpenAPI 3.0 using the content and schema properties. Example:

        @PostMapping("/users")
        @Operation(
            summary = "Create user",
            requestBody = @RequestBody(
                required = true,
                content = @Content(
                    schema = @Schema(implementation = User.class)
                )
            )
        )
        public ResponseEntity createUser(@RequestBody User user) {
            return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
        }
        

74. How do you document security requirements in OpenAPI 3.0?

Answer: You document security requirements in OpenAPI 3.0 by using the security attribute in your API definition, specifying the security scheme. Example:

        @OpenAPIDefinition(
            security = @SecurityRequirement(name = "bearerAuth")
        )
        public class ApiConfig {
            @Bean
            public SecurityScheme apiKeyScheme() {
                return new ApiKey("bearerAuth", "Authorization", In.HEADER);
            }
        }
        

75. How do you specify the response content type for different responses in Swagger?

Answer: You specify the response content type for different responses in Swagger using the @ApiResponse annotation with the producess

        @ApiOperation(value = "Get users by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success", response = User.class, produces = "application/json"),
            @ApiResponse(code = 500, message = "Internal Server Error", produces = "application/xml")
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

76. How do you document multiple response types for an API operation in OpenAPI?

Answer: You document multiple response types for an API operation in OpenAPI by defining multiple responses with different status codes and content types. Example:

        @GetMapping("/users/{id}")
        @Operation(
            summary = "Get user by ID",
            responses = {
                @ApiResponse(responseCode = "200", description = "User found", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
                @ApiResponse(responseCode = "404", description = "User not found", content = @Content(mediaType = "application/json"))
            }
        )
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

77. How do you add response headers to Swagger documentation?

Answer: You add response headers to Swagger documentation by using the @ApiResponse annotation with the responseHeaders attribute. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponse(
            code = 200,
            message = "User found",
            responseHeaders = @ResponseHeader(name = "X-Rate-Limit", description = "API rate limit", response = String.class)
        )
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

78. How do you define a default response in OpenAPI?

Answer: You define a default response in OpenAPI by using the default keyword in the responses section. Example:

        @Operation(
            responses = {
                @ApiResponse(responseCode = "200", description = "Success"),
                @ApiResponse(responseCode = "default", description = "Unexpected error")
            }
        )
        @GetMapping("/users")
        public List getAllUsers() {
            return userService.getAllUsers();
        }
        

79. How do you specify query parameters in OpenAPI?

Answer: You specify query parameters in OpenAPI by using the parameters array within the operation object. Example:

        @GetMapping("/users")
        @Operation(
            summary = "Search users by name",
            parameters = {
                @Parameter(name = "name", in = ParameterIn.QUERY, description = "Name of the user", required = true)
            }
        )
        public List searchUsers(@RequestParam String name) {
            return userService.searchUsers(name);
        }
        

80. How do you add authentication details to Swagger documentation?

Answer: You add authentication details to Swagger documentation by defining security schemes such as API key, OAuth2, or JWT. Example:

        @OpenAPIDefinition(
            security = @SecurityRequirement(name = "apiKey")
        )
        public class ApiConfig {
            @Bean
            public SecurityScheme apiKey() {
                return new ApiKey("apiKey", "Authorization", In.HEADER);
            }
        }
        

 

Set 9: API Versioning & Documentation (Swagger, OpenAPI)

81. How do you document the return type of an API operation in Swagger?

Answer: You document the return type of an API operation in Swagger using the @ApiResponse annotation with the response attribute. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User found", response = User.class)
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

82. How do you define a custom response status code in OpenAPI?

Answer: You define a custom response status code in OpenAPI using the responses section and specifying the status code along with the description. Example:

        @GetMapping("/users/{id}")
        @Operation(
            summary = "Get user by ID",
            responses = {
                @ApiResponse(responseCode = "200", description = "User found"),
                @ApiResponse(responseCode = "404", description = "User not found")
            }
        )
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

83. How do you document an error response with a custom message in Swagger?

Answer: You document an error response with a custom message in Swagger using the @ApiResponse annotation, including a custom message in the description. Example:

        @GetMapping("/users/{id}")
        @ApiResponses(value = {
            @ApiResponse(code = 404, message = "User not found"),
            @ApiResponse(code = 500, message = "Internal Server Error")
        })
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(userService.getUserById(id));
        }
        

84. How do you document API query parameters in Swagger?

Answer: You document API query parameters in Swagger using the @ApiParam annotation for each parameter. Example:

        @ApiOperation(value = "Get users by name")
        @GetMapping("/users")
        public List getUsersByName(@ApiParam(value = "Name of the user", required = true) @RequestParam String name) {
            return userService.getUsersByName(name);
        }
        

85. How do you specify the default value for a query parameter in Swagger?

Answer: You specify the default value for a query parameter in Swagger using the @ApiParam annotation with the defaultValue attribute. Example:

        @GetMapping("/users")
        public List getUsers(@ApiParam(value = "Page number", defaultValue = "1") @RequestParam int page) {
            return userService.getUsers(page);
        }
        

86. How do you document a list of items in a response in OpenAPI?

Answer: You document a list of items in a response in OpenAPI by using array and specifying the items property within the schema. Example:

        @Operation(
            summary = "Get list of users",
            responses = {
                @ApiResponse(responseCode = "200", description = "List of users", content = @Content(mediaType = "application/json", schema = @Schema(type = "array", implementation = User.class)))
            }
        )
        @GetMapping("/users")
        public List getAllUsers() {
            return userService.getAllUsers();
        }
        

87. How do you document response codes for different scenarios in OpenAPI?

Answer: You document response codes for different scenarios in OpenAPI by specifying multiple @ApiResponse annotations for each scenario. Example:

        @Operation(
            summary = "Create new user",
            responses = {
                @ApiResponse(responseCode = "201", description = "User created"),
                @ApiResponse(responseCode = "400", description = "Invalid input"),
                @ApiResponse(responseCode = "500", description = "Internal error")
            }
        )
        @PostMapping("/users")
        public ResponseEntity createUser(@RequestBody User user) {
            return ResponseEntity.status(HttpStatus.CREATED).body(userService.createUser(user));
        }
        

88. How do you document custom request headers in Swagger?

Answer: You document custom request headers in Swagger by using the @RequestHeader annotation and the @ApiParam annotation. Example:

        @GetMapping("/users")
        public List getUsers(@ApiParam(value = "Custom header for client ID") @RequestHeader("X-Client-ID") String clientId) {
            return userService.getUsersByClientId(clientId);
        }
        

89. How do you document the response content type in OpenAPI?

Answer: You document the response content type in OpenAPI by using the mediaType within the content property of the response. Example:

        @Operation(
            summary = "Get user profile",
            responses = {
                @ApiResponse(responseCode = "200", description = "User profile", content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
                @ApiResponse(responseCode = "400", description = "Invalid request")
            }
        )
        @GetMapping("/profile")
        public User getUserProfile() {
            return userService.getUserProfile();
        }
        

90. How do you enable Swagger for a Spring Boot application?

Answer: You enable Swagger in a Spring Boot application by adding the Swagger dependencies to the pom.xml file and annotating the main class with @EnableSwagger2. Example:

        @SpringBootApplication
        @EnableSwagger2
        public class Application {
            public static void main(String[] args) {
                SpringApplication.run(Application.class, args);
            }
        }
        

Set 10: API Versioning & Documentation (Swagger, OpenAPI)

91. How do you document path parameters in Swagger?

Answer: You document path parameters in Swagger using the @ApiParam annotation along with @PathVariable. Example:

        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(
            @ApiParam(value = "ID of the user", required = true) @PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

92. How do you document query parameters in OpenAPI?

Answer: You document query parameters in OpenAPI using the parameters section with the name, in, and description fields. Example:

        @Operation(
            summary = "Get users",
            parameters = @Parameter(name = "name", in = ParameterIn.QUERY, description = "Name of the user")
        )
        @GetMapping("/users")
        public List getUsers(@RequestParam String name) {
            return userService.getUsersByName(name);
        }
        

93. How do you document response codes in Swagger with different messages?

Answer: You document response codes with different messages in Swagger by using multiple @ApiResponse annotations for each status code. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User found"),
            @ApiResponse(code = 404, message = "User not found")
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

94. How do you generate an API documentation for a REST API in Spring Boot?

Answer: You generate API documentation in Spring Boot using Swagger by adding dependencies in the pom.xml and configuring Swagger in a configuration class. Example:

        @Configuration
        @EnableSwagger2
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build();
            }
        }
        

95. How do you specify the response content type in Swagger for a custom class?

Answer: You specify the response content type in Swagger for a custom class using the @ApiResponse annotation and the response attribute. Example:

        @ApiOperation(value = "Get user profile")
        @ApiResponse(code = 200, message = "User profile", response = User.class)
        @GetMapping("/profile")
        public User getUserProfile() {
            return userService.getUserProfile();
        }
        

96. How do you handle pagination in Swagger documentation?

Answer: You handle pagination in Swagger by documenting the query parameters for page size and page number, and using a response model that includes pagination details. Example:

        @GetMapping("/users")
        @Operation(
            summary = "Get users with pagination",
            parameters = {
                @Parameter(name = "page", description = "Page number", in = ParameterIn.QUERY),
                @Parameter(name = "size", description = "Page size", in = ParameterIn.QUERY)
            }
        )
        public Page getUsers(@RequestParam int page, @RequestParam int size) {
            return userService.getUsers(PageRequest.of(page, size));
        }
        

97. How do you document the API version in Swagger?

Answer: You document the API version in Swagger by specifying the version in the Docket bean configuration. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build()
                    .apiInfo(apiInfo());
        }

        private ApiInfo apiInfo() {
            return new ApiInfo(
                    "My API",
                    "API description",
                    "v1.0",
                    "Terms of service",
                    new Contact("Name", "www.example.com", "email@example.com"),
                    "License", "License URL", Collections.emptyList());
        }
        

98. How do you test API endpoints with Swagger UI?

Answer: You test API endpoints with Swagger UI by accessing the Swagger UI page in the browser and invoking the endpoints directly from the UI. Swagger UI provides an interactive interface to send requests and view responses for each documented API endpoint.

99. How do you enable the use of Swagger in a Spring Boot project?

Answer: You enable Swagger in a Spring Boot project by adding the necessary dependencies in the pom.xml file and configuring it with @EnableSwagger2. Example:

        
            io.springfox
            springfox-swagger2
            2.9.2
        
        
            io.springfox
            springfox-swagger-ui
            2.9.2
        
        

100. How do you document custom exception handling in Swagger?

Answer: You document custom exception handling in Swagger by specifying the response codes for different exceptions using @ApiResponse annotations for each error type. Example:

        @ApiResponses(value = {
            @ApiResponse(code = 400, message = "Invalid input"),
            @ApiResponse(code = 404, message = "Not Found")
        })
        @ExceptionHandler(CustomException.class)
        public ResponseEntity handleCustomException(CustomException ex) {
            return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
        }
        

 

Set 11: API Versioning & Documentation (Swagger, OpenAPI)

101. How do you add custom headers in OpenAPI documentation?

Answer: You add custom headers in OpenAPI documentation by specifying the headers property inside the @Operation annotation. Example:

        @Operation(
            summary = "Get user with custom header",
            parameters = @Parameter(name = "X-Custom-Header", in = ParameterIn.HEADER, description = "Custom header")
        )
        @GetMapping("/users/{id}")
        public ResponseEntity getUserById(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUserById(id));
        }
        

102. How can you create multiple API versions in a Spring Boot project?

Answer: You can create multiple API versions by adding versioning through request mapping and separating the APIs using path versioning. Example:

        @RestController
        @RequestMapping("/api/v1")
        public class UserControllerV1 {
            @GetMapping("/users")
            public List getUsersV1() {
                return userService.getUsers();
            }
        }

        @RestController
        @RequestMapping("/api/v2")
        public class UserControllerV2 {
            @GetMapping("/users")
            public List getUsersV2() {
                return userService.getUsersV2();
            }
        }
        

103. How do you handle authentication and authorization in Swagger documentation?

Answer: You handle authentication and authorization in Swagger documentation by using security and securitySchemes in the SwaggerConfig. Example:

        @Configuration
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                    .securitySchemes(Arrays.asList(new ApiKey("JWT", "Authorization", In.HEADER)))
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .build();
            }
        }
        

104. How do you enable filtering in Swagger UI?

Answer: You enable filtering in Swagger UI by setting the swagger-ui.filter property to true in the application.properties file. Example:

        swagger-ui.filter=true
        

105. How do you document response models in Swagger for complex objects?

Answer: You document response models in Swagger for complex objects using the @ApiResponse annotation and specifying the response model class. Example:

        @ApiOperation(value = "Get user details")
        @ApiResponse(code = 200, message = "Successful response", response = User.class)
        @GetMapping("/users/{id}")
        public ResponseEntity getUser(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUser(id));
        }
        

106. How do you handle versioning of API documentation?

Answer: You handle versioning of API documentation by using path versioning or header versioning. Path versioning is done by including the version in the URL, while header versioning uses HTTP headers. Example for path versioning:

        @RequestMapping("/api/v1")
        public class ApiControllerV1 {
            @GetMapping("/resource")
            public String getResource() {
                return "v1 resource";
            }
        }

        @RequestMapping("/api/v2")
        public class ApiControllerV2 {
            @GetMapping("/resource")
            public String getResource() {
                return "v2 resource";
            }
        }
        

107. How do you include an external documentation link in Swagger?

Answer: You include an external documentation link in Swagger by setting the externalDocs attribute in the Docket configuration. Example:

        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example"))
                .build()
                .externalDocs(new ExternalDocumentation()
                    .description("Full API Documentation")
                    .url("https://example.com/docs"));
        }
        

108. How do you use OpenAPI specification to define a custom object schema?

Answer: You use OpenAPI specification to define a custom object schema by defining the object using components.schemas. Example:

        @Schema(description = "User object")
        public class User {
            @Schema(description = "User ID", example = "1")
            private Long id;

            @Schema(description = "User name", example = "John Doe")
            private String name;

            // getters and setters
        }
        

109. How do you specify required fields in OpenAPI schema?

Answer: You specify required fields in OpenAPI schema by using the @Schema(required = true) annotation on the field. Example:

        @Schema(description = "User object")
        public class User {
            @Schema(description = "User ID", required = true)
            private Long id;

            @Schema(description = "User name", required = true)
            private String name;
        }
        

110. How do you manage different API documentation for different environments in Swagger?

Answer: You manage different API documentation for different environments in Swagger by setting different Swagger configuration profiles based on the environment (e.g., using @Profile annotations or external configuration). Example:

        @Configuration
        @Profile("dev")
        public class DevSwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build();
            }
        }
        

Set 12: API Versioning & Documentation (Swagger, OpenAPI)

111. How do you customize the default Swagger UI theme?

Answer: You can customize the default Swagger UI theme by overriding the default CSS styles with custom CSS files. This can be achieved by using the swagger-ui.css file. Example:

        
        

112. How do you generate Swagger documentation for multiple Spring Boot modules?

Answer: You generate Swagger documentation for multiple Spring Boot modules by creating a separate Docket bean for each module and then using @Import to bring them together. Example:

        @Configuration
        @Import({ Module1SwaggerConfig.class, Module2SwaggerConfig.class })
        public class SwaggerConfig {
            @Bean
            public Docket api() {
                return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.basePackage("com.example"))
                    .paths(PathSelectors.any())
                    .build();
            }
        }
        

113. How do you configure Swagger to only document specific methods?

Answer: You configure Swagger to only document specific methods by using the @ApiOperation annotation at the method level. Example:

        @ApiOperation(value = "Get user by ID", response = User.class)
        @GetMapping("/users/{id}")
        public ResponseEntity getUser(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUser(id));
        }
        

114. How do you include request parameters in Swagger documentation?

Answer: You include request parameters in Swagger documentation by using the @Parameter annotation for each parameter. Example:

        @GetMapping("/users")
        @Operation(summary = "Get users", parameters = {
            @Parameter(name = "age", description = "Age of the user", required = false)
        })
        public List getUsers(@RequestParam(required = false) Integer age) {
            return userService.getUsers(age);
        }
        

115. How do you document exceptions in Swagger?

Answer: You document exceptions in Swagger by using the @ApiResponse annotation to specify the error responses. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 404, message = "User not found"),
            @ApiResponse(code = 500, message = "Internal server error")
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUser(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUser(id));
        }
        

116. How do you include sample request and response data in Swagger?

Answer: You include sample request and response data in Swagger by using the @ApiModelProperty annotation and providing sample data. Example:

        @Schema(description = "User object")
        public class User {
            @Schema(description = "User ID", example = "1")
            private Long id;

            @Schema(description = "User name", example = "John Doe")
            private String name;
        }
        

117. How do you configure Swagger to show API responses based on status codes?

Answer: You configure Swagger to show API responses based on status codes by using the @ApiResponse annotation for each status code. Example:

        @ApiOperation(value = "Get user by ID")
        @ApiResponses(value = {
            @ApiResponse(code = 200, message = "User found", response = User.class),
            @ApiResponse(code = 404, message = "User not found")
        })
        @GetMapping("/users/{id}")
        public ResponseEntity getUser(@PathVariable Long id) {
            return ResponseEntity.ok(userService.getUser(id));
        }
        

118. How do you integrate Swagger with Spring Security?

Answer: You integrate Swagger with Spring Security by configuring security settings to allow Swagger UI to be accessed without authentication, or by adding custom security rules. Example:

        @Configuration
        public class SwaggerSecurityConfig extends WebSecurityConfigurerAdapter {
            @Override
            protected void configure(HttpSecurity http) throws Exception {
                http
                    .authorizeRequests()
                    .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
                    .anyRequest().authenticated();
            }
        }
        

119. How do you set up the API documentation for a Spring Boot project using OpenAPI 3.0?

Answer: You set up API documentation for a Spring Boot project using OpenAPI 3.0 by adding the springdoc-openapi dependency and configuring the OpenAPI bean. Example:

        @Configuration
        public class OpenAPIConfig {
            @Bean
            public OpenAPI customOpenAPI() {
                return new OpenAPI()
                    .info(new Info().title("API Documentation").version("1.0")
                        .description("This is the API documentation"));
            }
        }
        

120. How do you automatically generate Swagger documentation for new APIs in a Spring Boot project?

Answer: You automatically generate Swagger documentation for new APIs in a Spring Boot project by using the @RestController and @RequestMapping annotations, combined with Swagger annotations like @ApiOperation and @ApiResponse. Example:

        @RestController
        @RequestMapping("/api")
        @Api(tags = "User API")
        public class UserController {
            @ApiOperation(value = "Get all users", response = User.class)
            @GetMapping("/users")
            public List getUsers() {
                return userService.getUsers();
            }
        }